package com.lvmama.pet.sync.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.lvmama.bigger.biz.service.SyncTriggerHistoryServiceInterface;
import com.lvmama.bigger.biz.service.SyncTriggerServiceInterface;
import com.lvmama.bigger.biz.vo.SyncTriggerHistoryVo;
import com.lvmama.bigger.biz.vo.SyncTriggerVo;
import com.lvmama.bigger.common.data.domain.PageRequest;
import com.lvmama.bigger.common.data.domain.Pageable;
import com.lvmama.bigger.common.data.domain.Sort;
import com.lvmama.bigger.common.entity.search.SearchOperator;
import com.lvmama.bigger.common.entity.search.Searchable;
import com.lvmama.comm.bee.service.sync.SyncBaseNewService;
import com.lvmama.comm.bee.service.sync.SyncException;
import com.lvmama.comm.bee.service.sync.SyncNewException;
import com.lvmama.comm.sync.po.SyncMessage;
import com.lvmama.comm.sync.pojo.SyncTemplate;
import com.lvmama.comm.sync.pojo.SyncTemplateSql;
import com.lvmama.comm.sync.pojo.SyncTrigger;
import com.lvmama.comm.sync.utils.Constant;
import com.lvmama.comm.sync.utils.DateUtil;
import com.lvmama.comm.sync.utils.StringUtil;
import com.lvmama.comm.utils.MemcachedUtil;
import com.lvmama.pet.sync.dao.SyncMessageMapper;
import com.lvmama.pet.sync.dao.SyncTemplateMapper;
import com.lvmama.pet.sync.dao.SyncTemplateSqlMapper;
import com.lvmama.pet.sync.service.util.JDBCUtils;

/**
 * 
 * @author pengfei
 *
 */
public class SyncBaseNewServiceImpl implements SyncBaseNewService {

	@Autowired
	private SyncTemplateMapper syncTemplateMapper;
	
	@Autowired
	private SyncTemplateSqlMapper syncTemplateSqlMapper;
	
	@Autowired
	private SyncMessageMapper syncMessageMapper;
	
	
	private SyncTriggerServiceInterface biggerSyncTriggerService;
	
	private SyncTriggerHistoryServiceInterface biggerSyncTriggerHistoryService;
	
	static Log LOG = LogFactory.getLog(SyncBaseNewServiceImpl.class);
	
	protected void copyProperties(SyncTrigger source, SyncTriggerVo target) {
		if (source != null && target != null) {
			if(source.getTriggerId() != null) {
				target.setId(source.getTriggerId());
			}
			target.setUserName(source.getUserName());
			target.setTableName(source.getTableName());
			target.setPkValue(source.getPkValue());
			target.setStatus(source.getStatus());
			target.setCreateTime(source.getCreateTime());
			target.setTriggerType(source.getTriggerType());
			target.setDataSourceId(source.getDataSourceId());
			target.setFieldOne(source.getFieldOne());
			target.setFieldTwo(source.getFieldTwo());
			target.setFieldThree(source.getFieldThree());
			target.setpLevel(source.getpLevel());
			target.setServerName(source.getServerName());
			target.setPkBegin(source.getPkBegin());
			target.setPkQuantity(source.getPkQuantity());
			target.setCompleteCount(source.getCompleteCount());
			target.setSuccessNum(source.getSuccessNum());
			target.setFailNum(source.getFailNum());
			target.setRemark(source.getRemark());
			target.setBatchPkValue(source.getBatchPkValue());
		}
	}

	protected void copyProperties(SyncTriggerVo source, SyncTrigger target) {
		if (source != null && target != null) {
			target.setTriggerId(source.getId());
			target.setUserName(source.getUserName());
			target.setTableName(source.getTableName());
			target.setPkValue(source.getPkValue());
			target.setStatus(source.getStatus());
			target.setCreateTime(source.getCreateTime());
			target.setTriggerType(source.getTriggerType());
			target.setDataSourceId(source.getDataSourceId());
			target.setFieldOne(source.getFieldOne());
			target.setFieldTwo(source.getFieldTwo());
			target.setFieldThree(source.getFieldThree());
			target.setpLevel(source.getpLevel());
			target.setServerName(source.getServerName());
			target.setObjectId(source.getObjectId());
			target.setPkBegin(source.getPkBegin());
			target.setPkQuantity(source.getPkQuantity());
			target.setCompleteCount(source.getCompleteCount());
			target.setPkBegin(source.getPkBegin());
			target.setPkQuantity(source.getPkQuantity());
			target.setCompleteCount(source.getCompleteCount());
			target.setSuccessNum(source.getSuccessNum());
			target.setFailNum(source.getFailNum());
			target.setRemark(source.getRemark());
			if(StringUtils.isEmpty(source.getBatchPkValue())||"null".equals(source.getBatchPkValue())){
				target.setBatchPkValue("");
			}else{
				target.setBatchPkValue(source.getBatchPkValue());
			}

		}
	}
	
	protected void copyProperties(SyncTriggerVo source, SyncTriggerHistoryVo target) {
		if (source != null && target != null) {
			target.setId(source.getId());
			target.setUserName(source.getUserName());
			target.setTableName(source.getTableName());
			target.setPkValue(source.getPkValue());
			target.setStatus(source.getStatus());
			target.setCreateTime(source.getCreateTime());
			target.setTriggerType(source.getTriggerType());
			target.setDataSourceId(source.getDataSourceId());
			target.setFieldOne(source.getFieldOne());
			target.setFieldTwo(source.getFieldTwo());
			target.setFieldThree(source.getFieldThree());
			target.setpLevel(source.getpLevel());
			target.setProcessTime(source.getProcessTime());
			target.setServerName(source.getServerName());
			target.setObjectId(source.getObjectId());
			target.setPkValueNumber(source.getPkValueNumber());
			target.setFieldThreeNumber(source.getFieldThreeNumber());
			target.setBatchPkValue(source.getBatchPkValue());
		}
	}

	private Searchable getSearchable(Map<String, Object> params) {
		Searchable searchable = null;
		if(params != null) {
			Map<String, Object> searchParams = new LinkedHashMap<String, Object>();
			Object id = params.get("triggerId");
			if (id != null) {
				searchParams.put("id_" + SearchOperator.eq.name(), id);
			}
			Object userName = params.get("userName");
			if (userName != null) {
				searchParams.put("userName_" + SearchOperator.eq.name(), userName);
			}
			Object tableName = params.get("tableName");
			if (tableName != null) {
				searchParams.put("tableName_" + SearchOperator.eq.name(), tableName);
			}
			Object pkValue = params.get("pkValue");
			if (pkValue != null) {
				searchParams.put("pkValue_" + SearchOperator.eq.name(), pkValue);
			}
			Object status = params.get("status");
			if (status != null) {
				searchParams.put("status_" + SearchOperator.eq.name(), status);
			}
			Object createTime = params.get("createTime");
			if (createTime != null) {
				searchParams.put("createTime_" + SearchOperator.lte.name(), createTime);
			}
			Object triggerType = params.get("triggerType");
			if (triggerType != null) {
				searchParams.put("triggerType_" + SearchOperator.eq.name(), triggerType);
			}
			Object dataSourceId = params.get("dataSourceId");
			if (dataSourceId != null) {
				searchParams.put("dataSourceId_" + SearchOperator.eq.name(), dataSourceId);
			}
			Object fieldOne = params.get("fieldOne");
			if (fieldOne != null) {
				searchParams.put("fieldOne_" + SearchOperator.eq.name(), fieldOne);
			}
			Object fieldTwo = params.get("fieldTwo");
			if (fieldOne != null) {
				searchParams.put("fieldTwo_" + SearchOperator.eq.name(), fieldTwo);
			}
			Object fieldThree = params.get("fieldThree");
			if (fieldOne != null) {
				searchParams.put("fieldThree_" + SearchOperator.eq.name(), fieldThree);
			}
			Object pLevel = params.get("pLevel");
			if (pLevel != null) {
				searchParams.put("pLevel_" + SearchOperator.eq.name(), pLevel);
			}
			String serverName = Constant.getInstance().getServerName();
			if(StringUtils.isNotBlank(serverName)) {
				searchParams.put("serverName_" + SearchOperator.eq.name(), serverName);
			}
			searchable = Searchable.newSearchable(searchParams);
		}
		if (searchable == null) {
			searchable = Searchable.newSearchable();
		}
		return searchable;
	}
	
	private Searchable getSearchable(SyncTrigger trigger) {
		Searchable searchable = null;
		if(trigger != null) {
			Map<String, Object> searchParams = new LinkedHashMap<String, Object>();
			String id = trigger.getTriggerId();
			if (StringUtils.isNotBlank(id)) {
				searchParams.put("id_" + SearchOperator.eq.name(), id);
			}
			String userName = trigger.getUserName();
			if (StringUtils.isNotBlank(userName)) {
				searchParams.put("userName_" + SearchOperator.eq.name(), userName);
			}
			String tableName = trigger.getTableName();
			if (StringUtils.isNotBlank(tableName)) {
				searchParams.put("tableName_" + SearchOperator.eq.name(), tableName);
			}
			String pkValue = trigger.getPkValue();
			if (StringUtils.isNotBlank(pkValue)) {
				searchParams.put("pkValue_" + SearchOperator.eq.name(), pkValue);
			}
			String status = trigger.getStatus();
			if (StringUtils.isNotBlank(status)) {
				searchParams.put("status_" + SearchOperator.eq.name(), status);
			}
			Date createTime = trigger.getCreateTime();
			if (createTime != null) {
				searchParams.put("createTime_" + SearchOperator.lte.name(), createTime);
			}
			String triggerType = trigger.getTriggerType();
			if (StringUtils.isNotBlank(triggerType)) {
				searchParams.put("triggerType_" + SearchOperator.eq.name(), triggerType);
			}
			String dataSourceId = trigger.getDataSourceId();
			if (StringUtils.isNotBlank(dataSourceId)) {
				searchParams.put("dataSourceId_" + SearchOperator.eq.name(), dataSourceId);
			}
			String fieldOne = trigger.getFieldOne();
			if (StringUtils.isNotBlank(fieldOne)) {
				searchParams.put("fieldOne_" + SearchOperator.eq.name(), fieldOne);
			}
			String fieldTwo = trigger.getFieldTwo();
			if (StringUtils.isNotBlank(fieldTwo)) {
				searchParams.put("fieldTwo_" + SearchOperator.eq.name(), fieldTwo);
			}
			String fieldThree = trigger.getFieldThree();
			if (StringUtils.isNotBlank(fieldThree)) {
				searchParams.put("fieldThree_" + SearchOperator.eq.name(), fieldThree);
			}
			Long pLevel = trigger.getpLevel();
			if (pLevel != null) {
				searchParams.put("pLevel_" + SearchOperator.eq.name(), pLevel);
			}
			String serverName = trigger.getServerName();
			if(StringUtils.isNotBlank(serverName)) {
				searchParams.put("serverName_" + SearchOperator.eq.name(), serverName);
			}
			searchable = Searchable.newSearchable(searchParams);
		}
		if (searchable == null) {
			searchable = Searchable.newSearchable();
		}
		return searchable;
	}
	
	
	public List<SyncTrigger> findTriggerPageList(Map<String, Object> condition) {
		String serverName = Constant.getInstance().getServerName();
		if(StringUtils.isNotBlank(serverName)) {
			condition.put("serverName", serverName);
		}
		List<SyncTriggerVo> list = biggerSyncTriggerService.findListByParams(condition);
		List<SyncTrigger> resList = new ArrayList<SyncTrigger>();
		if(list !=null && !list.isEmpty()) {
			for (SyncTriggerVo vo : list) {
				SyncTrigger log = new SyncTrigger();
				copyProperties(vo, log);
				resList.add(log);
			}
		}
		return resList;
	}
	
	
	public List<SyncTrigger> findTriggerPageListWithTime(Map<String, Object> condition){
		String serverName = Constant.getInstance().getServerName();
		if(StringUtils.isNotBlank(serverName)) {
			condition.put("serverName", serverName);
		}
		condition.put("createTime", DateUtil.DsDay_Second(new Date(), -(int)(JDBCUtils.getDBSyncSecond()/(60*60*24))));
		List<SyncTriggerVo> list = biggerSyncTriggerService.findListByParams(condition);
		List<SyncTrigger> resList = new ArrayList<SyncTrigger>();
		if(list !=null && !list.isEmpty()) {
			for (SyncTriggerVo vo : list) {
				SyncTrigger log = new SyncTrigger();
				copyProperties(vo, log);
				resList.add(log);
			}
		}
		return resList;
	}
	
	/**
	 * 查询出符合条件的最大一条记录
	 * */
	private SyncTriggerVo findMaxNotInitST(Date date) {
		Map<String, Object> searchParams = new LinkedHashMap<String, Object>();
		String serverName = Constant.getInstance().getServerName();
		if(StringUtils.isNotBlank(serverName)) {
			searchParams.put("serverName_" + SearchOperator.eq.name(), serverName);
		}
		searchParams.put("status_" + SearchOperator.ne.name(), "INIT");
		searchParams.put("processTime_" + SearchOperator.lte, date);
		Searchable searchable = Searchable.newSearchable(searchParams);
		//按时间倒序
		Sort sortDesc = new Sort(Sort.Direction.DESC, "createTime");
		searchable.addSort(sortDesc);
		//只取第一条
		Pageable pageable = new PageRequest(0, 1);
		searchable.setPage(pageable);
		//按条件条件查询出符合条件的最大记录项
		List<SyncTriggerVo> list = biggerSyncTriggerService.findAllWithSort(searchable);
		if(list == null || list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}
	
	
	public Integer moveSyncTriggerData(Map paramMap) {
		Date date = DateUtil.getBeforeDayBySecond(Integer.parseInt(paramMap.get("time").toString()));
		//查询出符合条件的最大一条记录
		SyncTriggerVo vo = findMaxNotInitST(date);
		if(vo == null) {
			return 0;
		}
		String serverName = Constant.getInstance().getServerName();
		Object limitObj = paramMap.get("limit");
		if(limitObj == null) {
			return 0;
		}
		int limit = Integer.parseInt(limitObj.toString());
		boolean result = biggerSyncTriggerService.moveSyncTriggerData(vo.getObjectId(), serverName, limit);
		return result ? 1 : 0;
	}
	
	
	public Integer deleteSyncTriggerByParams(Map paramMap) {
		Date date = DateUtil.getBeforeDayBySecond(Integer.parseInt(paramMap.get("time").toString()));
		//查询出符合条件的最大一条记录
		SyncTriggerVo vo = findMaxNotInitST(date);
		if(vo == null) {
			return 0;
		}
		biggerSyncTriggerService.deleteByIds(vo.getObjectId(), Constant.getInstance().getServerName());
		return 1;
	}

	
	public Integer getCountAfterMoveSyncTriggerData(Map paramMap) {
		Integer rows = 0;
		Date date = DateUtil.getBeforeDayBySecond(Integer.parseInt(paramMap.get("time").toString()));
		SyncTriggerVo vo = findMaxNotInitST(date);
		if(vo == null) {
			return rows;
		}
		
		Map<String, Object> searchParams = new LinkedHashMap<String, Object>();
		String serverName = Constant.getInstance().getServerName();
		if(StringUtils.isNotBlank(serverName)) {
			searchParams.put("serverName_" + SearchOperator.eq.name(), serverName);
		}
		searchParams.put("status_" + SearchOperator.ne.name(), "INIT");
		searchParams.put("objectId_" + SearchOperator.lte, vo.getObjectId());
		Searchable searchable = Searchable.newSearchable(searchParams);
		Long count = biggerSyncTriggerService.count(searchable);
		return count == null ? 0 : count.intValue();
	}
	
	
	public int updateTriggersStatus(List<String> ids, String status) {
		if (ids == null || ids.size() == 0) {
			return 0;
		}
		Map<String, Object> params = new HashMap<String, Object>();
		if (ids.size() <= 1000) {
			params.put("ids", ids);
			params.put("status", status);
			biggerSyncTriggerService.updateStatusByIds(ids, status);
		}
		
		int count = 0;
		int rows = 0;
		List<String> tLs = new ArrayList<String>();
		for (int i = 0; i < ids.size(); i++) {
			tLs.add(ids.get(i));
			count++;
			if (count >= 999 || i == ids.size() - 1) {
				params.put("ids", tLs);
				params.put("status", status);
				rows += biggerSyncTriggerService.updateStatusByIds(ids, status);
				count = 0;
			}
		}
		return rows;
	}
	
	
	public SyncTemplate saveSyncTemplate(SyncTemplate template) {
		SyncTemplate old = syncTemplateMapper.findByUniqueKey(template);
		if (old != null) {
			throw new SyncNewException("数据源[" +
						Constant.SYNC_DATA_SOURCE.getCnName(template.getDataSourceId()) +
						"]用户名[" + template.getUserName() + "]表名[" + template.getTableName() + "]对应模板已经存在，不能重复");
		}
		syncTemplateMapper.insert(template);
		return template;
	}
	
	
	public SyncTemplate findSyncTemplateByUniqueKey(SyncTemplate template) {
		return syncTemplateMapper.findByUniqueKey(template);
	}
	
	
	public int updateSyncTemplate(SyncTemplate template) {
		SyncTemplate old = syncTemplateMapper.findByUniqueKey(template);
		if(old!=null){
			if(old.getTemplateId().intValue()!=template.getTemplateId().intValue()){
	        	throw new SyncNewException("数据源[" +
						Constant.SYNC_DATA_SOURCE.getCnName(template.getDataSourceId()) +
						"]用户名[" + template.getUserName() + "]表名[" + template.getTableName() + "]对应模板已经存在，不能重复");
	        }
		}
		String template_key = "TEMPLATE_"+template.getDataSourceId()+"_"+template.getTableName()+"_"+template.getUserName();
		MemcachedUtil.getInstance().remove(template_key);
		return syncTemplateMapper.update(template);
	}
	
	
	public SyncTemplate findSyncTemplateById(Long id) {
		return syncTemplateMapper.find(id);
	}
	
	
	public List<SyncTemplate> findSyncTemplatePageListByCondition(Map<String, Object> params) {
	
		return syncTemplateMapper.findPageListByCondition(params);
	}
	
	
	public Long countSyncTemplateByCondition(Map<String, Object> params) {
		return syncTemplateMapper.countByCondition(params);
	}
	
	
	public Long saveSyncTemplateSql(SyncTemplateSql templateSql) {
		if (Constant.SYNC_SQL_TYPE.SOURCE.name().equals(templateSql.getSqlType())) {
			templateSql.setSort(0);
		} else {
			Integer maxSort = syncTemplateSqlMapper.findMaxSort(templateSql);
			templateSql.setSort((maxSort==null?0:maxSort) + 1);
		}
		syncTemplateSqlMapper.insert(templateSql);
		return templateSql.getTemplateSqlId();
	}
	
	
	public int updateSyncTemplateSql(SyncTemplateSql templateSql) {
		String template_sql_key = "TEMPLATESQL_"+templateSql.getTemplateId()+"_"+templateSql.getTriggerType();
		MemcachedUtil.getInstance().remove(template_sql_key);
		return syncTemplateSqlMapper.update(templateSql);
	}
	
	
	public SyncTemplateSql findSyncTemplateSqlById(Long id) {
		return syncTemplateSqlMapper.find(id);
	}

	
	public List<SyncTemplateSql> findSyncTemplateSqlListByTemplateId(Long templateId) {
		return syncTemplateSqlMapper.findListByTemplateId(templateId);
	}
	
	
	public void resortSyncTemplateSql(Long id, String direction) {
		SyncTemplateSql sql = syncTemplateSqlMapper.find(id);
		if (sql == null) {
			return;
		}
		if (Constant.SYNC_SQL_TYPE.SOURCE.name().equals(sql.getSqlType())) {
			return;
		} else {
			if ("up".equals(direction) && Integer.valueOf(1).equals(sql.getSort())) {
				return;
			}
			Integer maxSort = syncTemplateSqlMapper.findMaxSort(sql);
			if ("down".equals(direction) && maxSort.equals(sql.getSort())) {
				return;
			} 
			SyncTemplateSql arg = new SyncTemplateSql();
			arg.setTemplateId(sql.getTemplateId());
			arg.setSqlType(sql.getSqlType());
			arg.setTriggerType(sql.getTriggerType());
			if ("up".equals(direction)) {
				arg.setSort(sql.getSort() - 1);
			} else {
				arg.setSort(sql.getSort() + 1);
			}
			Long sqlId = syncTemplateSqlMapper.findSQLIdBySort(arg);
			if (sqlId == null) {
				return;
			}
			if ("up".equals(direction)) {
				syncTemplateSqlMapper.down(sqlId);
				syncTemplateSqlMapper.up(id);
			} else {
				syncTemplateSqlMapper.up(sqlId);
				syncTemplateSqlMapper.down(id);
			}
		}
	}
	
	
	public List<SyncTemplateSql> findSyncTemplateSqlListByTargetTemplateSql(
			SyncTemplateSql sql) {
		return syncTemplateSqlMapper.findListByTargetTemplateSql(sql);
	}
	
	
	public void deleteSyncTemplateSqlById(Long templateSqlId) {
		syncTemplateSqlMapper.delete(templateSqlId);
	}

	
	public List<SyncTemplateSql> findTargetSyncTemplateSqlListByTemplateSql(
			SyncTemplateSql temp) {
		return syncTemplateSqlMapper.findTargetListByTemplateSql(temp);
	}

	
	public boolean checkSourceSyncTemplateSql(Long templateSqlId) {
		int count = syncTemplateSqlMapper.findUsingCountById(templateSqlId);
		return count > 0;
	}

	
	public List<SyncTemplate> findSyncTemplateListBySelects(List<String> templateIds) {
		return syncTemplateMapper.findListBySelects(templateIds);
	}

	
	public void deleteSyncTemplateSqlByTemplateId(Long templateId) {
		syncTemplateSqlMapper.deleteByTemplateId(templateId);
	}

	
	public void saveSyncTrigger(SyncTrigger trigger) {
		try {
			//对pkvalue进行 校验  非字符串型
			Long.parseLong(trigger.getPkValue());
			
			String status = trigger.getStatus();//为了用getSearchable方法，将值暂时保存
			trigger.setStatus("INIT");//初始化查询条件
			trigger.setCreateTime(new Date());
			String serverName = Constant.getInstance().getServerName();
			if(StringUtils.isNotBlank(serverName)) {
				trigger.setServerName(serverName);
			}
			Searchable searchable = getSearchable(trigger);
			Long count = biggerSyncTriggerService.count(searchable);
			if (count == 0) {
				trigger.setStatus(status);//重新设置原先的值
				trigger.setCreateTime(new Date());
				SyncTriggerVo vo = new SyncTriggerVo();
				copyProperties(trigger, vo);
				vo.setObjectId(System.currentTimeMillis());//long型，为了与com_log关联
			    String pkValue = vo.getPkValue();
			    if(StringUtil.isNumber(pkValue)) {//是数值
			    	vo.setPkValueNumber(Long.parseLong(pkValue));
			    }
			    String fieldThree = vo.getFieldThree();
			    if(StringUtil.isNumber(fieldThree)) {//是数值
			    	vo.setFieldThreeNumber(Long.parseLong(fieldThree));
			    }
				vo = biggerSyncTriggerService.save(vo);
			} else {
				LOG.warn(trigger + "已存在");
				throw new SyncNewException("任务已存在!");
			}
		}catch(NumberFormatException e){
			LOG.error("PKValue not expect");
			throw new RuntimeException(e);
		}catch (Exception e) {
			LOG.error(e);			
		}
	}
	
	
	public void saveSyncTrigger(String id, String userName, String tableName, String dataSourceId, String triggerType) {
		SyncTrigger trigger = createTrigger(id, userName, tableName, dataSourceId, triggerType);
		saveSyncTrigger(trigger);
	}
	
	
	public void saveSyncTrigger(String id, String userName, String tableName, String dataSourceId, String triggerType, String f1) {
		SyncTrigger trigger = createTrigger(id, userName, tableName, dataSourceId, triggerType);
		trigger.setFieldOne(f1);
		saveSyncTrigger(trigger);
	}
	
	
	public void saveSyncTrigger(String id, String userName, String tableName, String dataSourceId, String triggerType, String f1, String f2) {
		SyncTrigger trigger = createTrigger(id, userName, tableName, dataSourceId, triggerType);
		trigger.setFieldOne(f1);
		trigger.setFieldTwo(f2);
		saveSyncTrigger(trigger);
	}
	
	
	public void saveSyncTrigger(String id, String userName, String tableName, String dataSourceId, String triggerType, String f1, String f2, String f3) {
		SyncTrigger trigger = createTrigger(id, userName, tableName, dataSourceId, triggerType);
		trigger.setFieldOne(f1);
		trigger.setFieldTwo(f2);
		trigger.setFieldThree(f3);
		saveSyncTrigger(trigger);
	}
	
	
	public void deleteSyncMessageList(List<Long> idList) {
		if (idList.size() == 0) {
			return;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("idList", idList);
		syncMessageMapper.deleteList(map);
	}

	
	public List<SyncMessage> findSyncMessagePageList(Map<String, Object> params) {
		params.put("_startRow", 1);
		params.put("_endRow", params.get("rows"));
		return syncMessageMapper.findPageList(params);
	}

	
	public Integer getInitStatusTriggerCount(Map<String, Object> params) {
		params.put("status", "INIT");
		Searchable searchable = getSearchable(params);
		//按条件条件查询出符合条件的最大记录项
		Long count = biggerSyncTriggerService.count(searchable);
		return count == null ? 0 : count.intValue(); 
	}

	public void setsyncTemplateMapper(SyncTemplateMapper syncTemplateMapper) {
		this.syncTemplateMapper = syncTemplateMapper;
	}

	public void setsyncTemplateSqlMapper(SyncTemplateSqlMapper syncTemplateSqlMapper) {
		this.syncTemplateSqlMapper = syncTemplateSqlMapper;
	}

	public void setsyncMessageMapper(SyncMessageMapper syncMessageMapper) {
		this.syncMessageMapper = syncMessageMapper;
	}

	private SyncTrigger createTrigger(String id, String userName,
			String tableName, String dataSourceId, String triggerType) {
		SyncTrigger trigger = new SyncTrigger();
		trigger.setPkValue(id);
		trigger.setStatus(Constant.SYNC_STATUS.INIT.name());
		trigger.setUserName(userName);
		trigger.setTableName(tableName);
		trigger.setDataSourceId(dataSourceId);
		trigger.setTriggerType(triggerType);
		return trigger;
	}
	
	public int updatePLevelByParams(Map<String, Object> params) {
		if(params == null || params.get("pLevel") == null) {
			return 0;
		}
		String serverName = Constant.getInstance().getServerName();
		if(StringUtils.isNotBlank(serverName)) {
			params.put("serverName", serverName);
		}
		int count = biggerSyncTriggerService.updatePLevelByParams(params);
		return count;
	}
	
	
	@Override
	public int updateCompleteCountById(String triggerId, Long completeCount,Long successNum,Long failNum) {
		Map<String,Object> params =new HashMap<String, Object>();
		params.put("triggerId", triggerId);
		params.put("completeCount", completeCount);
		params.put("successNum", successNum);
		params.put("failNum", failNum);

		return biggerSyncTriggerService.updateCompleteCountById(params);
	}
	
	public static void main(String[] args) {
		System.out.println(new Date());
		Date date = DateUtil.DsDay_Second(new Date(), -(int)(JDBCUtils.getDBSyncSecond()/(60*60*24)));
		System.out.println(date);
	}

	public void setBiggerSyncTriggerService(
			SyncTriggerServiceInterface biggerSyncTriggerService) {
		this.biggerSyncTriggerService = biggerSyncTriggerService;
	}

	public void setBiggerSyncTriggerHistoryService(
			SyncTriggerHistoryServiceInterface biggerSyncTriggerHistoryService) {
		this.biggerSyncTriggerHistoryService = biggerSyncTriggerHistoryService;
	}

	/**
	 * 用户单个模板查看syncTrigger队列
	 * @param condition
	 * @return
	 */
	@Override
	public List<SyncTrigger> queryTriggerListPage(Map<String, Object> condition) {
		if(StringUtils.isEmpty(String.valueOf(condition.get("serverName")))){
			String serverName = Constant.getInstance().getServerName();
			condition.put("serverName", serverName);
		}
		
		List<SyncTriggerVo> list = biggerSyncTriggerService.findPageListByParams(condition);
		List<SyncTrigger> resList = new ArrayList<SyncTrigger>();
		if(list !=null && !list.isEmpty()) {
			for (SyncTriggerVo vo : list) {
				SyncTrigger log = new SyncTrigger();
				copyProperties(vo, log);
				resList.add(log);
			}
		}
		return resList;		
	}

	@Override
	public Long countSyncTrigger(Map<String, Object> params) {
		if(StringUtils.isEmpty(String.valueOf(params.get("serverName")))){
			String serverName = Constant.getInstance().getServerName();
			params.put("serverName", serverName);
		}
		return biggerSyncTriggerService.countSyncTrigger(params);
	}

	@Override
	public void deleteTemplateById(Long templateId) {
		syncTemplateMapper.deleteTemplateById(templateId);
		syncTemplateSqlMapper.deleteByTemplateId(templateId);
	}

	
	


}
